import { Component, OnInit } from '@angular/core';
import { Singlepage } from '../../model/singlepage';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { SinglepageService } from '../../service/singlepage.service';

@Component({
  selector: 'app-editsinglepage',
  templateUrl: './editsinglepage.component.html',
  styleUrls: ['./editsinglepage.component.css']
})
export class EditsinglepageComponent implements OnInit {
  singlepage:Singlepage;
  parm:string;
  selectedFile:string;

  constructor(
    private http:HttpClient,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private singlepageservice:SinglepageService,
  ) {
    this.singlepage=new Singlepage();
    this.parm=this.routerinfo.snapshot.params['id'];
   }

  ngOnInit() {
    if(this.parm=='add'){
      this.singlepage=new Singlepage();
    }else{
      this.getSinglepage(this.parm);
    }
  }

  save(){
    if(this.parm=='add'){
      this.addSinglepage();
    }
    else{
      this.updateSinglepage();
    }
  }

  goBack(){

    this.router.navigate(['uploadSinglepage']);
  
    }
  
  
    onFileChanged(event) {
      this.selectedFile = event.target.files[0];
    }
  
  
    onUpload() {
  
      const uploadData = new FormData();
    uploadData.append('file', this.selectedFile);
  
  
    this.http.post('http://www.baotr.xyz:81/manage/fileUpload',uploadData).subscribe(
      (data:any)=>{
   let host="http://www.baotr.xyz:81/public/";
   this.singlepage.img=host+data.img;
  
      },(err:HttpErrorResponse)=>{
        console.log(err.message);
      }
    )
  
    }
  
    private addSinglepage(){
  
      this.singlepageservice.addSinglepage(this.singlepage).then((flag:boolean)=>{
        if(flag==true){
          this.goBack();
        }
        else{
          alert('保存异常，请刷新后重试')
        }
      })
    }
  
  
  
  
    private updateSinglepage(){
      this.singlepageservice.updateSinglepage(this.singlepage)
      .then((flag)=>{
        if(flag==true){
          this.goBack();
        }else{
          alert("保存异常，请刷新重试");
        }
      })
    }
  
    private getSinglepage(id:string){
      this.singlepageservice.getSinglepage(id)
      .then((data:Singlepage)=>{
        if(data){
          this.singlepage=data;
        }else{
          alert("参数异常，请刷新后重试");
        }
      })
    }




}
